/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.starter.web.plugin;

import cn.hallele.infrastructure.metadata.constant.MsgCodeConst;
import cn.hallele.infrastructure.metadata.exception.HalException;
import cn.hallele.infrastructure.metadata.io.BatchResult;
import cn.hallele.infrastructure.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.ArrayList;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/11/16 17:58
 */
@Slf4j
public class BatchPlugin {
    private static final MessageSource I18N = SpringUtil.getBean(MessageSource.class);

    /**
     * 批量执行结果构造
     *
     * @param result  批量执行结果
     * @param e       异常
     * @param t       数据
     * @param success 执行结果
     * @param <T>     数据
     * @return BatchResult
     */
    public static <T> BatchResult<T> processBatch(BatchResult<T> result, Exception e, T t, Boolean success) {
        if (result == null) {
            result = BatchResult.<T>builder().data(new ArrayList<>(0)).build();
        }

        if (result.getData() == null) {
            result.setData(new ArrayList<>(0));
        }

        String msgCode;
        Object[] msgDesc = new Object[]{};
        if (e == null) {
            msgCode = MsgCodeConst.SUCCESS;
        } else if (e instanceof HalException halException) {
            msgCode = halException.getMessage();
            msgDesc = halException.getArgs();
        } else {
            msgCode = MsgCodeConst.FAILED;
            msgDesc = new Object[]{e.getMessage()};
        }

        String message = I18N.getMessage(msgCode, msgDesc, LocaleContextHolder.getLocale());
        result.getData().add(BatchResult.Result.<T>builder()
                .t(t)
                .result(success)
                .msgCode(msgCode)
                .msgDesc(message)
                .build());

        return result;
    }
}
